#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PROTECTED "freeze-safe."
#define LOG_FILE PROTECTED "logFile.txt"

int init_log(void);
int log_event(unsigned int u_id, char * buffer, int newFile, int regFile);

static FILE *logFile = 0;

/* Open the log file.  Create it, if it does not exist. */
int init_log() {
  logFile = fopen(LOG_FILE, "at");
  if (!logFile) logFile = fopen(LOG_FILE, "wt");
  if (!logFile) {
    printf("Error opening log file\n");
    return 0;
  }

  return 1;
}

// Check to see if the file is protected.

/* Log and copy the file that is being logged.
   Do a check to see if it is protected. Ignore
   the logging if it is.
*/
int log_event(unsigned int u_id, char * buffer, int newFile, int regFile) {
  FILE *source; 
  FILE *destination;
  char tempfile[128] = "/";
  char file_name[128] = PROTECTED;
  char ch;


  /* Print the information to the log file.
     Create a new file name with DNF.THIS.FILE.Unique_ID
  */
  fprintf(logFile, "%u\t%s\t%d\t%d\n", u_id, buffer, newFile, regFile);
  sprintf(file_name, "%s%u", file_name, u_id);


  /* Add a '/' to the beginning of the path name
     so it can properly open the file. Without
     it, the file does not open.
  */
  strcat(tempfile, buffer);
  strcpy(buffer, tempfile);

  /* Get the original file */
  source = fopen(buffer, "rb");
  if (source == NULL) {
    printf("Failed to open source file: %s\n", buffer);
    return 1;
  }

  /* Open a new file with the new specified
     file name DNF.THIS.FILE.u_id.
  */
  destination = fopen(file_name, "wb");
  if (destination == NULL) {
    printf("Failed to open destination file\n");
    fclose(source);
    return 1;
  }

  /* Copy all the bytes from one file
     to the other file.
  */
  while (!feof(source)) {
    ch = fgetc(source);
    if (ferror(source)) {
      printf("Error reading from source file.\n");    
      fclose(source);
      fclose(destination);
      return 1;
    }
    if (!feof(source)) fputc(ch, destination);
    if (ferror(destination)) {
      printf("Error writing to destination file.\n");
      fclose(source);
      fclose(destination);
      return 1;
    }
  }

  fclose(source);
  fclose(destination);

  return 1;
}

